package storagememory

import (
	"errors"
	"sync"
)

var ErrCacheEmpty = errors.New("cache is empty")

type Cache struct {
	m         map[string]*RingBuffer
	mux       sync.RWMutex
	cacheSize int
}

func New(size int) *Cache {
	c := &Cache{
		cacheSize: size,
		m:         make(map[string]*RingBuffer),
		mux:       sync.RWMutex{},
	}
	return c
}

func (c *Cache) GetRingBuffer(key string) *RingBuffer {
	// 先读锁获取
	c.mux.RLock()
	v, ok := c.m[key]
	c.mux.RUnlock()
	if ok {
		return v
	}

	// 再写锁创建
	c.mux.Lock()
	defer c.mux.Unlock()
	// 再检查一次，避免并发重复创建
	if v, ok = c.m[key]; ok {
		return v
	}

	v = NewKlineCache(c.cacheSize)
	c.m[key] = v
	return v
}

func (c *Cache) GetKey(symbol string, period string) string {
	return symbol + "_" + period
}
